package slh;

import slh.Book.BookDao;
import slh.movie.MovieDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/search")
public class SerchSevlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        // 获取请求参数
        String keyword = request.getParameter("keyword");
        String type = request.getParameter("type");

        // 创建结果列表
        List<Object> results = new ArrayList<>();

        try {
            // 根据类型搜索电影或图书
            if (keyword != null && !keyword.trim().isEmpty()) {
                if ("all".equals(type) || "movie".equals(type)) {
                    results.addAll(MovieDao.searchMovies(keyword));
                }
                if ("all".equals(type) || "book".equals(type)) {
                    results.addAll(BookDao.searchBooks(keyword));
               }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "搜索过程中发生数据库错误");
        }

        // 设置结果并转发到JSP
        request.setAttribute("results", results);
        request.setAttribute("keyword", keyword);
        request.setAttribute("type", type);
        request.getRequestDispatcher("slh/searchResults.jsp").forward(request, response);
    }
}